package iReportDemo;


import java.sql.*;
import java.util.*;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

public class JasperReportWrapper {

	public Connection connectToDB() {

		String username = "root";
		String password = "";
		Connection con;
		String url = "jdbc:mysql://localhost/soffo_db";
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			con = DriverManager.getConnection(url, username, password);
			if (con != null) {
				System.out.println("Successfully connected to the database");
			}
			return con;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public JasperReport compileJRXMLFile() {

		String filename = "Reports\\MyReports\\Blank_A4.jrxml";
	
		JasperReport report;

		try {
			report = JasperCompileManager.compileReport(filename);
			if (report != null) {
				System.out.println("Your Report compiled successfully");
			}

			return report;
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
	
	public JasperPrint fillReport(JasperReport report, Map<String, Object> parameters, Connection con)
	{
		if(con != null)
		{
			try {
				JasperPrint print = JasperFillManager.fillReport(report,parameters,con);
				if(print != null)
				{
					System.out.println("Your Report filled with application data");
					
				}
				return print; 
			} catch (JRException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return null;
	}
	
	public void saveReportInPDF(JasperPrint jasperPrint, String pdfFileName)
	{
		try {
			JasperExportManager.exportReportToPdfFile(jasperPrint,pdfFileName);
			System.out.println("Your Report successfully saved in PDF");
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
